package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;

    //保存用户搜索历史记录
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDTO userSearchDto) {
        //获取搜索关键词和行为实体id
        Integer entryId = userSearchDto.getEntryId();
        String searchWords = userSearchDto.getSearchWords();
        //根据entryId查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorEntryResponseResult = behaviorFeign.findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        //检查响应
        if (!behaviorEntryResponseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorEntryResponseResult.getData();
        //检查响应
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查构建查询条件
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("keyword").is(searchWords));
        //查询当前关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //非空判断
        if (apUserSearch == null) {
            //不存在,直接新增
            apUserSearch = new ApUserSearch();
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setEntryId(apBehaviorEntry.getId());
            apUserSearch.setKeyword(searchWords);
            mongoTemplate.save(apUserSearch);
        } else {
            //存在,更新时间
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }
    }

    //查询搜索历史
    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        //获取当前用户
        Integer userId = AppThreadLocalUtils.getUser().getId();
        //非空判断
        if (userId == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据userId查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorEntryResp = behaviorFeign.findByUserIdOrEquipmentId(userId, userSearchDto.getEquipmentId());
        //检查响应
        if (!behaviorEntryResp.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResp.getData();
        //根据行为实体,查询数据库的搜索词历史
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        //非空判断
        if (apUserSearches.size() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //数据存在,根据时间降序,取10条
        List<ApUserSearch> collect = apUserSearches.stream().sorted(Comparator.comparing(ApUserSearch::getCreatedTime).reversed()).limit(10).collect(Collectors.toList());
        //返回结果
        return ResponseResult.okResult(collect);
    }

    //删除搜索历史记录
    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        //获取当前登录用户
        Integer userId = AppThreadLocalUtils.getUser().getId();
        if (userId == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询行为实体
        ResponseResult<ApBehaviorEntry> ApBehaviorEntryResp = behaviorFeign.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        //检查响应
        if (!ApBehaviorEntryResp.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取数据
        ApBehaviorEntry ApBehaviorEntry = ApBehaviorEntryResp.getData();
        //根据entryId和历史记录id查询数据库并删除
        Query query = Query.query(Criteria.where("entryId").is(ApBehaviorEntry.getId()).and("id").is(dto.getId()));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult();
    }
}